package com.sxd.bill.rela.item;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.Data;

@Data
public class TemplateResult {
    private Map<String, String> matchedResult;
    private String matchedText;
    private int matchedTextStartIndex;
    private int matchedTextEndIndex;
    private String matchedRawText;

    private static TemplateResult emptyInstance = new TemplateResult(new HashMap<>(), "", 0, 0, "");

    /**
     * 返回空结果
     * 
     * @return
     */
    public static TemplateResult ofEmpty() {
        return emptyInstance;
    }

    public TemplateResult(Map<String, String> matchedResult, String matchedText,
            int matchedTextStartIndex, int matchedTextEndIndex, String matchedRawText) {
        this.matchedResult = matchedResult;
        this.matchedText = matchedText;
        this.matchedTextStartIndex = matchedTextStartIndex;
        this.matchedTextEndIndex = matchedTextEndIndex;
        this.matchedRawText = matchedRawText;
    }

    public int size() {
        return matchedResult.size();
    }

    /**
     * 获取第一个实体的起始索引位置
     * 
     * @return
     */
    public int getFirstEntityStartIndex() {
        return matchedResult.entrySet().stream().map(e -> matchedText.indexOf(e.getValue()) + matchedTextStartIndex)
                .min(Integer::compareTo).orElse(null);
    }

    public List<Map<String, String>> getRelationMaps() {
        Map<Integer, Map<String, String>> numGroups = new HashMap<>();
        Map<String, String> baseGroup = new HashMap<>();
        Pattern digitPattern = Pattern.compile("\\d+$");
        // 拆分成通用共同部分和不同后缀数字（标签名称后缀数字）部分
        for (Map.Entry<String, String> entry : matchedResult.entrySet()) {
            String groupName = entry.getKey();
            Matcher mg = digitPattern.matcher(groupName);
            if (mg.find()) {
                int num = Integer.parseInt(mg.group());
                String newGroupName = groupName.replaceAll("\\d+$", "");
                if (!numGroups.containsKey(num)) {
                    numGroups.put(num, new HashMap<>());
                }
                numGroups.get(num).put(newGroupName, entry.getValue());
            } else {
                baseGroup.put(groupName, entry.getValue());
            }
        }
        // 对上面的拆分结果，进行组装
        List<Map<String, String>> items = new ArrayList<>();
        if (!numGroups.isEmpty()) {
            for (Map.Entry<Integer, Map<String, String>> entry : numGroups.entrySet()) {
                Map<String, String> item = entry.getValue();
                item.putAll(baseGroup);
                items.add(item);
            }
        } else if (!baseGroup.isEmpty()) {
            items.add(baseGroup);
        }
        return items;
    }
}
